﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Entity.IRepository.Project;
using Entity.ProjectEnt;
using Logic.Repository.Project;
using ZFine.Code;
using ZFine.Domain.Entity;

namespace ZFine.Application.Project
{
    public class PathwayApp
    {
        private IPathwayRepository service = new PathwayRepository();
        private IGudaoCarRepository gudaocarservice=new GudaoCarRepository();
        private PositionRecordApp positoonapp = new PositionRecordApp();
        private IHistoryGudaoCarRepository historygudaocarservice=new HistoryGudaoCarRepository();
        private  IOperationGudaoCarRepository operationgudaoservice=new OperationGudaoCarRepository();
        private OperationGudaoCarApp operService = new OperationGudaoCarApp();
        private GudaoCarApp gudaoApp = new GudaoCarApp();
      

        public List<PathwayEntity> GetList()
        {
            return service.IQueryable().ToList();
        }
        public List<PathwayEntity> GetList(Expression<Func<PathwayEntity, bool>> predicate)
        {
            return service.IQueryable(predicate).ToList();
        }
        public List<PathwayEntity> GetListN()
        {
            var expression = ExtLinq.True<PathwayEntity>();
            expression = expression.And(t => t.State == true);
            return service.IQueryable(expression).OrderBy(f=>f.ShowSort).ToList();
            //return service.FindList(expression, pagination);
        }

        public List<PathwayEntity> GetList(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<PathwayEntity>();
            expression = expression.And(t => t.State == true);
            return service.FindList(expression, pagination);
        }
        public List<PathwayEntity> GetListD(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<PathwayEntity>();
            expression = expression.And(t => t.State == true);
            return service.FindList(expression, pagination);
        }
        public PathwayEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public int DeleteForm(string keyValue)
        {
            List<GudaoCarEntity> gudaoCarList = gudaoApp.GetList(f=>f.State==true&&f.BelongPathway.F_Id==keyValue);
            if (gudaoCarList.Count!=0)
            {
                return -2;
            }

            List<OperationGudaoCarEntity> operList = operService.GetList(f=>f.State==true&&f.OperationType==2&&f.IsExecute!=true);
            if (operList.Count!=0)
            {
                return -3;
            }
            var expression = ExtLinq.True<PathwayEntity>();
            expression = expression.And(t => t.F_Id == keyValue);
            var result = service.FindEntity(expression);
            if (result != null)
            {
                result.State = false;
                return service.UpdateN(result);
            }
            else
            {
                return -1;
            }
        }
        public int SubmitForm(PathwayEntity ServiceEntity, string keyValue)
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            if (LoginInfo != null)
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    var expression = ExtLinq.True<PathwayEntity>();
                    expression = expression.And(t => t.F_Id == keyValue);
                    var result = service.FindEntity(expression);
                    result.Name = ServiceEntity.Name;
                    result.Length = ServiceEntity.Length;
                    result.IsCounterpoint = ServiceEntity.IsCounterpoint;
                    result.IsPaiche = ServiceEntity.IsPaiche;
                    result.IsPermitThrough = ServiceEntity.IsPermitThrough;
                    result.IsStatistics = ServiceEntity.IsStatistics;
                    result.F_LastModifyTime = DateTime.Now;
                    result.ShowSort = ServiceEntity.ShowSort;
                    result.State = true;
                    return service.UpdateN(result);
                }
                else
                {
                    ServiceEntity.Create();
                    ServiceEntity.State = true;
                    return service.Insert(ServiceEntity);
                }
            }
            else
            {
                return -1;
            }
           
            
        }

        /// <summary>
        /// 清除股道中信息
        /// </summary>
        /// <param name="keyValue">股道名字</param>
        /// <param name="msg">返回消息</param>
        /// <returns></returns>
        public int ClearCarinfo(string keyValue, ref string msg)
        {
            int code = 0;
            #region 判断是否有没有执行的计划
            OperationGudaoCarEntity NotExecutePlayWork =
                  operationgudaoservice.FindEntityAsNoTracking(f =>
                      f.State == true && f.OperationType == 2 && f.IsExecute == false);
            if (NotExecutePlayWork != null)
            {
                code = -1;
                msg = "有未执行的计划，请先执行计划或者删除计划完成后，再进行排车操作";
                return code;
            }
            #endregion
            var gudao = service.FindEntityAsNoTracking(f => f.State == true && f.Name == keyValue);
            if (gudao != null) {
                if (gudao.IsPaiche == false) {
                    code = -1;
                    msg = "此股道禁止排车，无法进行此操作";
                    return code;
                }
            }
            List<GudaoCarEntity> gudaocarlist = gudaocarservice.GetIncludeList(f => f.BelongPathway.Name == keyValue&&f.State==true);
            if (gudaocarlist != null && gudaocarlist.Count > 0)
            {
                OperationGudaoCarEntity operation=new OperationGudaoCarEntity();
                operation.Create();
                operation.State = true;
                operation.OperationTime = DateTime.Now;
                operation.OperationType =6;
                operation.IsRollBack = false;
                var loginInfo = OperatorProvider.Provider.GetCurrent();
                if (loginInfo != null)
                {
                    operation.OperationPersion = new UserEntity() { F_Id = loginInfo.UserId };
                }
                var thispaiban = positoonapp.GetForm(f => f.State == true);
                if (thispaiban != null)//有效班期id
                {
                    operation.Banci = thispaiban.F_Id;
                }
                List<HistoryGudaoCarEntity> historygudaocarlist=new List<HistoryGudaoCarEntity>();
                for (int i = 0; i < gudaocarlist.Count; i++)
                {
                    gudaocarlist[i].ClearGudaoOper=new OperationGudaoCarEntity();
                    gudaocarlist[i].ClearGudaoOper = operation;
                }
                foreach (var item in gudaocarlist)
                {
                    item.isAccomplishPaiche = true;
                    item.AccomplishPaicheTime = DateTime.Now;
                    HistoryGudaoCarEntity temp=new HistoryGudaoCarEntity();
                    temp.Create();
                    temp.ThingsName = item.ThingsName;
                    temp.Fenhao = item.Fenhao;
                    temp.isQiPiao = item.isQiPiao;
                    temp.QiPiaoTime = item.QiPiaoTime;
                    temp.ArriveDateTime = item.ArriveDateTime;
                    temp.isAccomplishStatistics = item.isAccomplishStatistics;
                    temp.AccomplishStatisticsTime = item.AccomplishStatisticsTime;
                    temp.IsAccomplishPermitThrough = item.IsAccomplishPermitThrough;
                    temp.AccomplishPermitThroughTime = item.AccomplishPermitThroughTime;
                    temp.isAccomplishPaiche = item.isAccomplishPaiche;
                    temp.AccomplishPaicheTime = item.AccomplishPaicheTime;
                    temp.IsAccomplishduiwei = item.IsAccomplishduiwei;
                    temp.AccomplishduiweiTime = item.AccomplishduiweiTime;
                    temp.Remark = item.Remark;
                    temp.ArriveStation = item.ArriveStation;
                    temp.Weight = item.Weight;
                    temp.UnitNumber = item.UnitNumber;
                    temp.Customers = item.Customers;
                    temp.State = item.State;
                    temp.BelongPathway = item.BelongPathway;
                    temp.BelongCarriage = item.BelongCarriage;
                    temp.Operation = item.Operation;
                    temp.PassOper = item.PassOper;
                    temp.QiPiaoOper = item.QiPiaoOper;
                    temp.ClearGudaoOper = operation;
                    temp.WorkPlanOper = item.WorkPlanOper;
                    historygudaocarlist.Add(temp);
                }
                code = service.SubmitClearCarinfo(gudaocarlist, historygudaocarlist, operation);
                if (code > 0)
                {
                    msg = "操作成功";
                }
                else
                {
                    msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                code = -1;
                msg = "此股道中无车辆，无法进行排车操作";
            }
            return code;
        }

        /// <summary>
        /// 回退清除股道中信息
        /// </summary>
        /// <param name="keyValue">股道名字</param>
        /// <param name="msg">返回消息</param>
        /// <returns></returns>
        public int RetClearCarinfo(string keyValue, ref string msg)
        {
            int code = 0;
            List<GudaoCarEntity> gudaocarhaslist = gudaocarservice.GetIncludeList(f => f.BelongPathway.Name==keyValue&&f.State==true);
            if (gudaocarhaslist != null && gudaocarhaslist.Count > 0)
            {
                msg = "此股道中现有车辆,无法完成回退操作";
                return -7;
            }
            //var operation=operationgudaoservice.FindEntityAsNoTracking(f=>f.OperationType==6)

            //修改------回退最新一次的排车
            var thiselementlist = historygudaocarservice.FindListBelongandClera(f => f.BelongPathway.Name == keyValue && f.State == true && f.ClearGudaoOper.OperationType == 6 && f.ClearGudaoOper.IsRollBack == false).OrderByDescending(f => f.AccomplishPaicheTime).GroupBy(f => f.ClearGudaoOper.F_Id);
            List<HistoryGudaoCarEntity> gudaocarlist = thiselementlist.FirstOrDefault().ToList();
            //List<HistoryGudaoCarEntity> gudaocarlist = historygudaocarservice.FindListBelongandClera(f =>f.BelongPathway.Name == keyValue&&f.State==true&&f.ClearGudaoOper.OperationType==6&&f.ClearGudaoOper.IsRollBack==false).OrderByDescending(f=>f.AccomplishPaicheTime).GroupBy(f=>f.ClearGudaoOper.F_Id);
            
            if (gudaocarlist != null && gudaocarlist.Count > 0)
            {
                if (gudaocarlist[0].ClearGudaoOper == null)
                {
                    msg = "无回退操作记录O,无法完成回退操作";
                    return -6;
                }
                //获取当前上班的人员
                var positionrecord = positoonapp.GetForm(f => f.State == true);
                if (positionrecord.F_Id != gudaocarlist[0].ClearGudaoOper.Banci)
                {
                    
                    msg = "班次不同，无法完成回退操作";
                    return -5;//返回 当前班次与统计运量班次不对应！不能进行此操作
                }
                var cleargudaooperid = gudaocarlist.OrderByDescending(f=>f.F_CreatorTime).FirstOrDefault().ClearGudaoOper.F_Id;
                List<GudaoCarEntity> retgudaocarlist = gudaocarservice.GetIncludeList(f => f.ClearGudaoOper.F_Id== cleargudaooperid);
                if (retgudaocarlist != null && retgudaocarlist.Count > 0)
                {
                    if (retgudaocarlist.Count == gudaocarlist.Count || retgudaocarlist.Count < gudaocarlist.Count)//一个股道有一次回退操作或多次回退操作，按照最后一次的操作进行回退
                    {
                        var operationid = retgudaocarlist.FirstOrDefault();
                        if (operationid != null && operationid.ClearGudaoOper!=null)
                        {
                            var opid = operationid.ClearGudaoOper.F_Id;
                            var operation = operationgudaoservice.FindEntity(f => f.F_Id == opid);
                            if (operation != null)
                            {
                                operation.IsRollBack = true;
                                operation.RollbackTime = DateTime.Now;
                                code = service.SubmitRetClearlist(gudaocarlist, retgudaocarlist, operation);
                            }
                            else
                            {
                                return -3;
                            }
                        }
                        if (code == -3)
                        {
                            msg = "无回退操作任务,无法执行回退";
                        }
                        else if (code < 0)
                        {
                            msg = "回退操作失败，请稍后重试";
                        }
                        else
                        {
                            msg = "回退成功";
                        }
                    }
                    else
                    {
                        var log = LogFactory.GetLogger(this.GetType().ToString());
                        log.Error(DateTime.Now + ":回退股道排车发生错误，历史股道车辆数和股道车辆数量不同,historylist.count:" + gudaocarlist.Count + ",gudaocarlist.count:" + retgudaocarlist.Count);
                        code = -1;
                        msg = "回退股道排车发生错误，历史股道车辆数和股道车辆数量不同";
                    }
                }
                else
                {
                    var log = LogFactory.GetLogger(this.GetType().ToString());
                    log.Error(DateTime.Now + ":回退股道排车发生错误，retgudaocarlist股道车辆数量为空");
                    msg = "此股道中没有要回退的车辆信息";
                    code = -1;
                }
            }
            else
            {
                msg = "此股道中没有要回退的车辆信息";
                code = -1;
            }
            return code;
        }


        public List<PathwayEntity> GetList(Pagination pagination)
        {
            var expression = ExtLinq.True<PathwayEntity>();
            expression = expression.And(t => t.State == true);
            return service.FindList(expression, pagination);
             
        }

        public int GetGuDaoCarNum(string keyValue)
        {
            int result =0;
            if (!string.IsNullOrEmpty(keyValue))
            {
                string sql = string.Format("SELECT count(*) as Num FROM [dbo].[GudaoCar] WHERE BelongPathway_F_Id='{0}'",keyValue);
                result = service.FindListthis(sql);
            }
            return result;
        }



    }
}
